package com.hyt.it.ogt.ksmonitor.statistics.mq;

import com.hyt.it.ogt.ksmonitor.statistics.config.StatisticsMqProperties;
import com.hyt.it.ogt.ksmonitor.statistics.config.StatisticsPropertyFactory;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@Slf4j
@ConditionalOnClass({Channel.class, RabbitTemplate.class, RabbitAdmin.class})
@PropertySource(value = "classpath:application-monitor-statistics.yml", factory = StatisticsPropertyFactory.class)
@ConfigurationProperties(prefix  = "mq.topic.monitor")
public class StatisticsRabbitMqConfig {

    @Bean
    public StatisticsMqProperties monitorStatisticsMqProperties(@Value("${mq.monitorstatistics.exchange}") String monitorStatisticsExchange,
                                                                @Value("${mq.monitorstatistics.queue}") String monitorStatisticsQueue,
                                                                       @Value("${mq.monitorstatistics.route}") String monitorStatisticsRoute) {
        StatisticsMqProperties properties = new StatisticsMqProperties();
        properties.setMonitorStatisticsExchange(monitorStatisticsExchange);
        properties.setMonitorStatisticsQueue(monitorStatisticsQueue);
        properties.setMonitorStatisticsRoute(monitorStatisticsRoute);
        return properties;
    }

    @Bean
    public DirectExchange monitorStatisticsExchange(RabbitAdmin rabbitAdmin, StatisticsMqProperties monitorStatisticsMqProperties) {
        Exchange exchange = ExchangeBuilder.directExchange(monitorStatisticsMqProperties.getMonitorStatisticsExchange()).durable(true).build();
        rabbitAdmin.declareExchange(exchange);
        return (DirectExchange) exchange;
    }

    @Bean
    public Queue monitorStatisticsQueue(RabbitAdmin rabbitAdmin, StatisticsMqProperties monitorStatisticsMqProperties) {
        Queue queue = new Queue(monitorStatisticsMqProperties.getMonitorStatisticsQueue());
        rabbitAdmin.declareQueue(queue);
        return queue;
    }

    @Bean
    Binding monitorStatisticsBinding(RabbitAdmin rabbitAdmin, StatisticsMqProperties monitorStatisticsMqProperties) {
        return BindingBuilder.bind(this.monitorStatisticsQueue(rabbitAdmin, monitorStatisticsMqProperties))
                .to(monitorStatisticsExchange(rabbitAdmin, monitorStatisticsMqProperties))
                .with(monitorStatisticsMqProperties.getMonitorStatisticsRoute());
    }

}
